package x.ovo.wechat.bot.http.request.contact;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import x.ovo.wechat.bot.common.Constant;
import x.ovo.wechat.bot.common.entity.Contact;
import x.ovo.wechat.bot.common.http.request.ApiRequest;
import x.ovo.wechat.bot.common.http.session.LoginSession;

import java.util.List;
import java.util.function.Function;

public class ContactListRequest extends ApiRequest<List<Contact>> {


    public ContactListRequest(LoginSession session) {
        super(session);
    }

    @Override
    public String getUrl() {
        return UrlBuilder.of(this.session.getUrl())
                .addPath(Constant.GET_CONTACT)
                .addQuery("r", System.currentTimeMillis())
                .addQuery("lang", "zh_CN")
                .addQuery("pass_ticket", this.session.getPassTicket())
                .addQuery("skey", this.session.getSKey())
                .addQuery("seq", 0)
                .build();
    }

    @Override
    public Function<String, List<Contact>> responseHandler() {
        return s -> {
            JSONObject object = JSONUtil.parseObj(s);
            if (object.getJSONObject("BaseResponse").getInt("Ret") == 0) {
                return JSONUtil.toList(object.getJSONArray("MemberList"), Contact.class);
            }
            return List.of();
        };
    }

}
